﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WcfContrib.Client.Description;
using System.ServiceModel;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using WcfContrib.Client;
using WcfContrib.Client.Behaviors;
using WcfContrib.Helpers;

namespace WcfContrib.Extensions.Behaviors
{
    /// <summary>
    /// A behavior that increases the max items in object graph to the maximum value and boosts the binding.
    /// </summary>
    public class BoostedEndpointBehaviorAttribute : Attribute, IEndpointBehavior, IClientEndpointBehavior, IClientChannelHandlerBehavior
    {
        #region IEndpointBehavior Members
        void IEndpointBehavior.ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
        {
        }

        void IEndpointBehavior.AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
        {
            ApplyBoosting(endpoint);
        }

        void IEndpointBehavior.ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
            ApplyBoosting(endpoint);
        }

        void IEndpointBehavior.Validate(ServiceEndpoint endpoint)
        {
        }
        #endregion

        #region IClientEndpointBehavior Members

        void IClientEndpointBehavior.ApplyClientBehavior(ClientChannel clientChannel, ClientEndpointDescription endpointDescription)
        {
            endpointDescription.ChannelHandlers.AddUnique(this);
        }

        #endregion

        #region IClientChannelHandlerBehavior Members

        void IClientChannelHandlerBehavior.ChannelFactoryCreated(ClientChannel clientChannel, ChannelFactory factory)
        {
            ApplyBoosting(factory.Endpoint);
        }

        void IClientChannelHandlerBehavior.ChannelCreated(ClientChannel clientChannel, ICommunicationObject channel)
        {
        }

        #endregion

        void ApplyBoosting(ServiceEndpoint endpoint)
        {
            endpoint.TryBoosting();
        }
    }
}
